<template>
    <page-container>
        <div class="flex property-wrap left-right-wrap">
            <div class="left-wrap">
                <left-tree pageType="1" :isMedical="true" v-model:checked="queryParams.projectCodes" @checked="handleTreeCheck"></left-tree>
            </div>
            <div class="right-wrap">
                <div class="ant-pro-table">
                    <div class="ant-pro-table-search">
                        <a-form layout="horizontal">
                            <a-row :gutter="16" type="flex" justify="start">
                                <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                    <a-form-item>
                                        <a-range-picker
                                            v-model:value="queryParams.actualTime"
                                            style="width: 100%"
                                            :placeholder="['收款开始时间', '收款结束时间']"
                                            allow-clear
                                            @change="handleSearch()"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                    <a-form-item>
                                        <a-cascader
                                            v-model:value="queryParams.deptIds"
                                            style="width: 100%"
                                            multiple
                                            :placeholder="'请选择科室'"
                                            :options="buildData"
                                            :field-names="{ label: 'name', value: 'id', children: 'children' }"
                                            :change-on-select="false"
                                            :show-checked-strategy="Cascader.SHOW_CHILD"
                                            :max-tag-count="1"
                                            @change="handleSearch()"
                                        ></a-cascader>
                                    </a-form-item>
                                </a-col>
                                <!-- <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select ref="select" v-model:value="queryParams.serviceTypeIds"
                                            placeholder="陪护类型" mode="multiple" :options="
                                                typesData.map(item => ({
                                                    ...item,
                                                    label: item.name,
                                                    value: item.id,
                                                }))
                                            " :max-tag-count="1" allow-clear @change="handleSearch()"></a-select>
                                    </a-form-item>
                                </a-col> -->
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-input v-model:value="queryParams.carerName" allow-clear placeholder="护工名称" @change="handleSearch()"></a-input>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select
                                            ref="select"
                                            v-model:value="queryParams.paymentType"
                                            placeholder="缴款方式"
                                            :options="[
                                                { label: '通联', value: 0 },
                                                { label: '现金', value: 3 },
                                            ]"
                                            allow-clear
                                            @change="handleSearch()"
                                        ></a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select
                                            ref="select"
                                            v-model:value="queryParams.refundOccurs"
                                            placeholder="账单方式"
                                            :options="[
                                                { label: '收入', value: 0 },
                                                { label: '退款', value: 1 },
                                            ]"
                                            allow-clear
                                            @change="handleSearch()"
                                        ></a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="24" :sm="24" :md="12" :lg="4">
                                    <a-button @click="handleReset" class="ml-5px">重置</a-button>
                                </a-col>
                            </a-row>
                        </a-form>
                    </div>
                    <a-card :body-style="{ padding: 0 }" ref="elRef">
                        <div class="ant-pro-table-list-toolbar">
                            <div class="ant-pro-table-list-toolbar-container">
                                <div class="ant-pro-table-list-toolbar-left flex items-center">
                                    <!-- <div class="ant-pro-table-list-toolbar-title">财务报表</div> -->
                                    <div class="flex ant-pro-table-list-toolbar-left-rflex">
                                        <a-typography-text strong underline>总收入：{{ totalCount.total || 0 }}</a-typography-text>
                                        <a-typography-text strong underline>通联收款：{{ totalCount.onlinePayment || 0 }}</a-typography-text>
                                        <a-typography-text strong underline>现金收款：{{ totalCount.cashPayment || 0 }}</a-typography-text>
                                        <a-typography-text strong underline>通联退款：{{ totalCount.onlineRefund || 0 }}</a-typography-text>
                                        <a-typography-text strong underline>现金退款：{{ totalCount.cashRefund || 0 }}</a-typography-text>
                                        <a-typography-text strong underline>净收入：{{ totalCount.payment || 0 }}</a-typography-text>
                                    </div>
                                </div>
                                <div class="ant-pro-table-list-toolbar-right">
                                    <a-space align="center">
                                        <a-button @click="handleExport" class="ml-10px" :loading="exportLoading" v-permission="[`yfwy:medical-caregiver-order:export`]">
                                            <download-outlined />
                                            导出
                                        </a-button>
                                    </a-space>
                                    <div class="ant-pro-table-list-toolbar-divider">
                                        <a-divider type="vertical" />
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="刷新">
                                            <reload-outlined @click="reload" />
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="密度">
                                            <a-dropdown :trigger="['click']" placement="bottomRight">
                                                <column-height-outlined />
                                                <template #overlay>
                                                    <a-menu
                                                        style="width: 80px"
                                                        :selected-keys="[state.tableSize]"
                                                        @click="
                                                            ({ key }) => {
                                                                fetchDataContext.tableSize = String(key);
                                                            }
                                                        "
                                                    >
                                                        <a-menu-item key="default">
                                                            <a href="javascript:;">默认</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="middle">
                                                            <a href="javascript:;">中等</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="small">
                                                            <a href="javascript:;">紧凑</a>
                                                        </a-menu-item>
                                                    </a-menu>
                                                </template>
                                            </a-dropdown>
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-popover placement="bottomRight" arrowPointAtCenter trigger="click" overlayClassName="ant-pro-table-column-setting-overlay">
                                            <template #title>
                                                <div class="ant-pro-table-column-setting-title">
                                                    <a-checkbox v-model:checked="columnState.checkAll" :indeterminate="columnState.indeterminate" @change="handleColumnAllClick">
                                                        列展示 / 排序
                                                    </a-checkbox>
                                                    <a @click="reset">重置</a>
                                                </div>
                                            </template>
                                            <template #content>
                                                <span class="ant-pro-table-column-setting-list">
                                                    <drag-container
                                                        lockAxis="y"
                                                        dragClass="ant-pro-table-drag-ghost"
                                                        dropClass="ant-pro-table-drop-ghost"
                                                        @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)"
                                                    >
                                                        <template :key="column.key" v-for="column in dynamicColumnItems">
                                                            <draggable>
                                                                <div class="ant-pro-table-column-setting-list-item">
                                                                    <drag-icon />
                                                                    <a-checkbox :checked="column.checked" @change="handleColumnChange($event, column)">
                                                                        {{ column.label }}
                                                                    </a-checkbox>
                                                                </div>
                                                            </draggable>
                                                        </template>
                                                    </drag-container>
                                                </span>
                                            </template>
                                            <a-tooltip title="列设置">
                                                <setting-outlined />
                                            </a-tooltip>
                                        </a-popover>
                                    </div>
                                    <!-- <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip :title="screenState ? '退出全屏' : '全屏'">
                                            <fullscreen-outlined v-if="!screenState" @click="setFull" />
                                            <fullscreen-exit-outlined v-else @click="exitFull" />
                                        </a-tooltip>
                                    </div> -->
                                </div>
                            </div>
                        </div>
                        <a-table
                            row-key="id"
                            :size="state.tableSize"
                            :loading="state.loading"
                            :columns="dynamicColumns"
                            :data-source="state.dataSource"
                            :pagination="{
                                'show-size-changer': true,
                                current: state.current,
                                pageSize: state.pageSize,
                                total: state.total,
                                showTotal: total => `共 ${total} 条`,
                            }"
                            :scroll="{ x: 1150, y: appStore.tableHeight - 68 }"
                            ref="tableRef"
                            :getPopupContainer="_trigger => tableRef.$el"
                            @change="handleTableChange"
                        >
                            <template #bodyCell="{ record, column }">
                                <template v-if="column.dataIndex === 'advertisingImage'">
                                    <a-image :width="80" :src="record.advertisingImage" />
                                </template>
                                <template v-if="column.dataIndex === 'display'">
                                    <span v-if="record.display == 1">是</span>
                                    <span v-if="record.display == 0">否</span>
                                </template>
                            </template>
                        </a-table>
                    </a-card>
                </div>
            </div>
        </div>
    </page-container>
</template>

<script lang="ts">
    import { defineComponent, reactive, ref, onMounted } from 'vue';
    import {
        PlusOutlined,
        ReloadOutlined,
        ColumnHeightOutlined,
        SettingOutlined,
        DownOutlined,
        FullscreenOutlined,
        FullscreenExitOutlined,
        DeleteOutlined,
        HighlightOutlined,
        DownloadOutlined,
    } from '@ant-design/icons-vue';
    import { Container as DragContainer, Draggable } from '@/components/draggable';
    import { getFinancialStatementPage, exportFinancialStatementList, getTotalCount } from '@/api/companion/finance';
    import type { Pagination, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useFullscreen } from '@/utils/hooks/useFullscreen';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import DragIcon from '@/components/table/drag-icon.vue';
    import type { TableColumnsType } from 'ant-design-vue';
    import { useAppStore } from '@/store/app';
    import { queryDeptsByProjectcodes } from '@/api/list/department';
    import { recursionMapTree } from '../porter/common';
    import { message, Cascader } from 'ant-design-vue';
    import { paymentTypeMap } from '../order/common';
    import { downloadByData } from '@/utils/download';
    import { getMedicalCaregiverTypePage } from '@/api/companion/cate';
    import { isEmpty } from 'lodash-es';
    import dayjs from 'dayjs';
    import { add } from 'xe-utils';

    const appStore = useAppStore();
    const baseColumns: TableColumnsType[] = [
        {
            title: '基础信息',
            children: [
                {
                    title: '收款日期',
                    dataIndex: 'payTime',
                    align: 'center',
                },
                {
                    title: '订单号',
                    dataIndex: 'orderNum',
                    align: 'center',
                    ellipsis: true,
                },
                {
                    title: '科室',
                    align: 'center',
                    dataIndex: 'departmentName',
                    ellipsis: true,
                },
                {
                    title: '床位',
                    dataIndex: 'bedNum',
                    align: 'center',
                },
                {
                    title: '收费开始日期',
                    dataIndex: 'actualStartTime',
                    width: 110,
                    align: 'center',
                },
                {
                    title: '收费截止日期',
                    dataIndex: 'actualEndTime',
                    width: 110,
                    align: 'center',
                },
                {
                    title: '服务天数',
                    dataIndex: 'actualDay',
                    align: 'center',
                },
                {
                    title: '服务模式',
                    dataIndex: 'serviceTypeName',
                    align: 'center',
                    width: 120,
                    ellipsis: true,
                },
                {
                    title: '患者姓名',
                    dataIndex: 'patientName',
                    align: 'center',
                },
            ],
        },
        {
            title: '缴费信息',
            children: [
                // {
                //     title: '现金金额',
                //     dataIndex: 'name',
                // },
                // {
                //     title: '银行金额',
                //     dataIndex: 'advertisingImage',
                // },
                {
                    title: '金额合计',
                    dataIndex: 'payPrice',
                    align: 'center',
                },
                {
                    title: '缴款方式',
                    dataIndex: 'paymentType',
                    align: 'center',
                },
                {
                    title: '护工名称',
                    dataIndex: 'carerName',
                    align: 'center',
                },
            ],
        },
    ];
    export default defineComponent({
        name: 'Finance',
        setup() {
            const tableRef = ref();
            const {
                state: columnState,
                dynamicColumns,
                dynamicColumnItems,
                handleColumnAllClick,
                handleColumnChange,
                reset,
                move,
            } = useTableDynamicColumns(baseColumns, { needRowIndex: false });
            const queryParams = reactive<any>({
                projectCodes: '',
                deptIds: [],
                serviceTypeIds: [],
            });
            const [elRef, screenState, { setFull, exitFull }] = useFullscreen();
            const fetchDataContext = reactive({
                current: 1,
                pageSize: 10,
                tableSize: 'middle', // 'default' | 'middle' | 'small'
                stripe: true,
                isList: false,
                executeImmediately: false,
                requestParams: {
                    ...queryParams,
                },
            });
            const { reload, context: state } = useFetchData(getFinancialStatementPage, fetchDataContext);
            const treeData = ref<any[]>([]);
            const buildData = ref<any[]>([]);
            const typesData = ref<any[]>([]);

            const totalCount = ref<any>({});
            // 表格数据和加载
            const handleTableChange = ({ current, pageSize }: Pagination) => {
                fetchDataContext.current = current;
                fetchDataContext.pageSize = pageSize;
            };

            const handleSearch = () => {
                const { actualTime = [], deptIds = [], ...params } = queryParams;

                if (!isEmpty(actualTime) && actualTime.length === 2) {
                    params.start = dayjs(actualTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
                    params.end = dayjs(actualTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
                }
                if (deptIds.length > 0) {
                    params.deptIds = deptIds.map(item => item.at(-1));
                }
                fetchDataContext.current = 1;
                fetchDataContext.requestParams = { ...params };

                getTotalCount(params).then(res => {
                    if (!isEmpty(res.data)) {
                        totalCount.value = {
                            ...res.data,
                            total: add(res.data.onlinePayment, res.data.cashPayment),
                        };
                    }
                });
            };

            const handleReset = () => {
                Object.keys(queryParams).forEach(key => {
                    if (key != 'projectCode' && key != 'buildingIds') {
                        delete queryParams[key];
                    }
                });
                handleSearch();
            };

            onMounted(() => {
                Promise.all([
                    getMedicalCaregiverTypePage({
                        current: 1,
                        size: 10000,
                    }),
                ]).then(res => {
                    const [cateData] = res;
                    typesData.value = cateData.data.records;
                });
            });

            const exportLoading = ref<boolean>(false);
            const handleExport = () => {
                exportLoading.value = true;
                exportFinancialStatementList({
                    ...fetchDataContext.requestParams,
                    size: 1000000000,
                })
                    .then(res => {
                        downloadByData(res, `财务报表.xlsx`);
                    })
                    .finally(() => {
                        exportLoading.value = false;
                    });
            };

            const handleTreeCheck = (
                checkedKeys,
                e: any,
                // e: { checked: boolean; checkedNodes; node; event },
            ) => {
                queryParams.projectCodes = checkedKeys;
                queryParams.deptIds = [];

                fetchDataContext.executeImmediately = true;
                handleSearch();

                queryDeptsByProjectcodes(checkedKeys).then(res => {
                    // 查询科室
                    buildData.value = recursionMapTree(res.data, 1, 4);
                });
            };

            return {
                handleTreeCheck,
                appStore,
                tableRef,
                handleSearch,
                queryParams,
                reload,
                state,
                columnState,
                dynamicColumns,
                dynamicColumnItems,
                // fullscreen
                elRef,
                screenState,
                setFull,
                exitFull,
                handleTableChange,
                handleColumnChange,
                handleColumnAllClick,
                reset,
                move,
                fetchDataContext,
                handleReset,
                treeData,
                buildData,
                Cascader,
                paymentTypeMap,
                handleExport,
                exportLoading,
                typesData,
                totalCount,
            };
        },
        components: {
            DragIcon,
            PlusOutlined,
            ReloadOutlined,
            ColumnHeightOutlined,
            SettingOutlined,
            FullscreenOutlined,
            FullscreenExitOutlined,
            Draggable,
            DownOutlined,
            DragContainer,
            DeleteOutlined,
            HighlightOutlined,
            Cascader,
            DownloadOutlined,
        },
    });
</script>

<style lang="less" scoped>
    .ant-pro-table-list-toolbar-left-rflex {
        & > span {
            margin-right: 20px;
        }
    }
</style>
